package com.company.project.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.company.project.bean.GType;
import com.company.project.bean.Goods;
import com.company.project.dao.GoodsDao;

public class GoodsDaoImpl extends HibernateDaoSupport  implements GoodsDao {


	
	@Override
	public List<?> findAll() {
		// TODO Auto-generated method stub
		List<?> list = this.getHibernateTemplate().find("from Goods");
		
		return list;
	}

	
	/*public Goods findById(Integer id) {
		// TODO Auto-generated method stub
		System.out.println("dao...................");
		List<?> list = this.getHibernateTemplate().find("from Goods where id ='id'");
		System.out.println("dao2......................2");
		return (Goods) list.get(0);
	}*/
	@Override
	public List<?> findById(int id) {
		// TODO Auto-generated method stub
		Session session = getSession();
		Query query = session.createQuery("from Goods where id=:id");
		query.setParameter("id", id);
		return  query.list();
		
		
	}


	@Override
	public void save(Goods goods) {
		// TODO Auto-generated method stub
		this.getHibernateTemplate().update(goods);
	}


	@Override
	public List<?> findByProperty(String propertyName, Object id2) {
		String sql = "from Goods as goods where goods."+propertyName+"=?";
		return getHibernateTemplate().find(sql, id2);
	}

	
	@Override
	public int getTotalPage(int pagesize){
		int rowTotal=getHibernateTemplate().find("from Goods").size();
		int total=rowTotal/pagesize;
		if(rowTotal%pagesize>0){
			total++;
		}
		return total;
	}
	
	public List<?> getPage(int currentPage){
		Session session = getSession();
		
		/*Session session = getHibernateTemplate().getSessionFactory().getCurrentSession(); */
		/*if(session==null){
			session = this.getHibernateTemplate().getSessionFactory().openSession();
		}*/
		Query query = session.createQuery("from Goods");
		query.setMaxResults(7);
		query.setFirstResult((currentPage-1)*7);
		return query.list();
	}


	@Override
	public List<?> findByGid(int id) {
		// TODO Auto-generated method stub
		List list= this.getHibernateTemplate().find("from Goods where id="+id);
		System.out.println(list);
		return list;
	}


	@Override
	public List<?> findByName(String keywords) {
		// TODO Auto-generated method stub
		DetachedCriteria criteria=DetachedCriteria.forClass(Goods.class);
		criteria.add(Restrictions.like("goodsname","%"+keywords+"%"));
		
		return getHibernateTemplate().findByCriteria(criteria);
		
	}


	
	

}
